﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"

int NumberMine(char mine[ROWS][COLS],int x,int y)
{//统计该坐标周围雷的数量，八个方向的坐标
	int i, j, count = 0;
	for (i = x - 1; i <= x + 1; i++)
	{
		for (j = y - 1; j <= y + 1; j++)
		{
			if (mine[i][j] == '#')
			{
				count++;
			}
		}
	}
	return count;

	
}
void InitBoard(char board[ROWS][COLS], int rows, int cols, char set)
{
	int i, j;
	for (i = 0; i < rows; i++)
	{
		for (j = 0; j < cols; j++)
		{
			board[i][j] = set;//用set存放传过来的任意字符
		}
	}
}

void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
	int i, j;
	printf("----------扫雷游戏----------\n");
	for (i = 0; i <= row; i++)//打印横坐标
	{
		printf("%-2d ", i);
	}
	printf("\n");
	for (i = 1; i <= row; i++)
	{
		printf("%-2d ", i);
		for (j = 1; j <= col; j++)
		{
			printf("%c  ", board[i][j]);
		}
		printf("\n");
	}
	printf("----------扫雷游戏----------\n");
}

void SetMine(char board[ROWS][COLS], int row, int col)
{
	int x, y, count = 0;
	while (count != EASY)
	{
		x = rand() % ROW + 1;//x=1~9
		y = rand() % COL + 1;//y=1~9
		if (board[x][y] == '0')
		{
			board[x][y] = '#';//用'#'表示雷
			count++;
		}
	}
}


void SearchBlank(char mine[ROWS][COLS], char show[ROWS][COLS], int x, int y)
{
	if (x >= 1 && x <= ROW && y >= 1 && y <= COL)
	{
		if (show[x][y] != '*')//如果该坐标已经下过了，则返回
			return;
		int count = NumberMine(mine,x,y);//调用函数统计该坐标周围雷的数量
		if (count != 0)//如果该坐标周围有雷，则直接显示该坐标的数字
		{
			show[x][y] = count + '0';
			return;
		}
		if (count == 0)
		{
			show[x][y] = '0';//如果该坐标周围没有雷，则显示'0'
			int extend[8][2] = { {0,1},{0,-1},{1,0},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1} };
			for (int i = 0; i < 8; i++)
			{
				SearchBlank(mine, show, x + extend[i][0], y + extend[i][1]);
			}
		}
	}
}
void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
	int x, y, count = 0, i, j;
	while (1)
	{
		printf("请输入排雷坐标:");
		scanf("%d %d", &x, &y);
		if (x >= 1 && x <= row && y >= 1 && y <= col)
		{
			if (show[x][y] != '*')//如果该坐标已经下过了
			{
				printf("该坐标已经下过了，请重新输入\n");
				continue;
			}
			else if (mine[x][y] == '#')//如果该坐标是雷
			{
				printf("很遗憾，你被炸死了\n");
				DisplayBoard(mine, ROW, COL);
				break;
			}
		/*	else if (mine[x][y] == '0')
			{
				int ret = 0;
				ret = NumberMine(mine, x, y);
				show[x][y] = ret + '0';

				DisplayBoard(show, ROW, COL);
				count--;
			}*/
		
			else
			{//如果该坐标不是雷，则调用函数搜索其他空白区域
				SearchBlank(mine, show, x, y);//寻找空白区域
				DisplayBoard(show, ROW, COL);
			}
		}
		else
		{
			rewind(stdin);//清空缓冲区,如果玩家输入非法字符，则清空缓冲区
			printf("坐标非法，请重新输入\n");
			continue;
		}
		for (i = 1; i <= row; i++)
		{
			for (j = 1; j <= col; j++)
			{
				if (show[i][j] != '*')
				{
					count++;//统计排雷的次数
				}
			}
		}
		if (count == ROW * COL - EASY)
		{
			printf("恭喜你，你排出了所有的雷\n");
			DisplayBoard(mine, ROW, COL);
			break;
		}
	}
}